package server

import (
	"strconv"
	"time"

	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/ratelimit"
	"github.com/go-kratos/kratos/v2/transport/grpc"

	pbButton "gitee.com/danqingzhao/go-dango/api/user/button/v1"
	pbCustomer "gitee.com/danqingzhao/go-dango/api/user/customer/v1"
	pbMenu "gitee.com/danqingzhao/go-dango/api/user/menu/v1"
	pbPermission "gitee.com/danqingzhao/go-dango/api/user/permission/v1"
	pbRole "gitee.com/danqingzhao/go-dango/api/user/role/v1"
	data "gitee.com/danqingzhao/go-dango/apps/user/data"
	service "gitee.com/danqingzhao/go-dango/apps/user/service"
	core "gitee.com/danqingzhao/go-dango/pkg/common/core"
	settings "gitee.com/danqingzhao/go-dango/pkg/proto/settings"
)

// NewGRPCServer new a gRPC server.
func NewGRPCServer(
	c *settings.ServerConf,
	loggers *settings.Loggers,
	logHelpers *settings.LogHelpers,
	permission *service.PermissionService,
	menu *service.MenuService,
	button *service.ButtonService,
	role *service.RoleService,
	customer *service.CustomerService,
	d *data.Data,
) *grpc.Server {
	var opts = []grpc.ServerOption{
		grpc.Middleware(
			core.Recovery(logHelpers.Server),
			ratelimit.Server(),
			logging.Server(loggers.Access),
			core.AuthMiddleware(logHelpers.Server, d.Casbin),
			core.ProtoValidate(),
		),
	}
	addr := c.Grpc.Host + ":" + strconv.Itoa(int(c.Grpc.Port))
	opts = append(opts, grpc.Address(addr))
	timeout := time.Duration(c.Grpc.Timeout)
	opts = append(opts, grpc.Timeout(timeout))
	srv := grpc.NewServer(opts...)
	pbPermission.RegisterPermissionServer(srv, permission)
	pbMenu.RegisterMenuServer(srv, menu)
	pbButton.RegisterButtonServer(srv, button)
	pbRole.RegisterRoleServer(srv, role)
	pbCustomer.RegisterCustomerServer(srv, customer)
	return srv
}
